package fun.shuofeng.juc.completableFuture;

import java.sql.Time;
import java.util.concurrent.*;
import java.util.function.BiConsumer;

/**
 * @author 朔风
 * @date 2024-02-28 23:50
 */
public class CompletableFutureUseDemo {
    public static void main(String[] args) throws InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "---- come in");
                // 模拟耗时任务，睡眠一秒钟
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (result > 3) {
                    int a = 1 / 0;
                }
                return result;
            }, threadPool).whenComplete((result, e) -> {
                if (e == null) {
                    System.out.println("----异步计算完毕，更新系统update value：" + result);
                }
            }).exceptionally(e -> {
                System.out.println("异常情况：" + e.getMessage());
                return null;
            });
        } finally {
            threadPool.shutdown();
        }

        System.out.println(Thread.currentThread().getName() + "主线程先去忙了");
        // 让主线程等等异步任务，因为主线程一销毁，异步任务就无法打印出结果
        TimeUnit.SECONDS.sleep(2);

    }
}
